import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'logic.dart';

class MotionPage extends StatelessWidget {
  MotionPage({super.key});

  final logic = Get.put(MotionLogic());
  final state = Get.find<MotionLogic>().state;
  bool isLongPress = false;
  late Timer timer;

  @override
  Widget build(BuildContext context) {
    logic.setSportsGoalAndDrawRouteLine();

    return WillPopScope(
      onWillPop: () => Future.value(false),
      child: Scaffold(
        body: Column(
          children: [
            SizedBox(height: 180.h),
            Container(
              margin: EdgeInsets.all(38.w),
              width: 1.sw,
              height: 163.h,
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text(LocaleKeys.sports_in_motion_text.ts, style: TextStyle(color: Colors.black, fontSize: 49.sp)),
                  // Text(Type.i18nNameBy(state.goalInfo['workoutType']), style: TextStyle(color: Colors.black, fontSize: 49.sp)),
                  state.isShowMap
                      ? Row(
                          children: [
                            Text('GPS', style: TextStyle(color: Colors.black, fontSize: 49.sp)),
                            SizedBox(width: 10.w), //signal
                            GetBuilder<MotionLogic>(
                              id: 'gps_signal',
                              builder: (_) {
                                return Image.asset('assets/images/sports/icon_gps_${state.signal}.png', width: 85.w, height: 46.h);
                              },
                            )
                          ],
                        )
                      : Container(width: 400.w),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 38.w, right: 38.w),
              padding: EdgeInsets.only(top: 40.h),
              width: 1.sw,
              height: 490.h,
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10)),
              child: GetBuilder<MotionLogic>(
                  id: logic.realTimeData,
                  builder: (_) {
                    String goal = logic.getGoalInfo();
                    return Column(
                      children: [
                        SizedBox(width: 60.h),
                        GetBuilder<MotionLogic>(
                          id: logic.realTimeData,
                          builder: (_) => RichText(
                            text: TextSpan(children: [
                              TextSpan(
                                  text: logic.getRealTimeDistanceText(), style: TextStyle(fontSize: 63.sp, color: Colors.black)),
                              TextSpan(text: '  ', style: TextStyle(fontSize: 36.sp, color: ColorConst.btnFontColor)),
                              TextSpan(text: logic.getLengthUnitString(), style: TextStyle(fontSize: 36.sp, color: ColorConst.btnFontColor)),
                            ]),
                          ),
                        ),
                        SizedBox(height: 20.h),
                        if (goal.isNotEmpty && goal != '--')
                          RichText(
                            text: TextSpan(children: [
                              TextSpan(text: LocaleKeys.sports_goal_text.ts, style: TextStyle(fontSize: 37.sp, color: ColorConst.secondaryFontColor)),
                              TextSpan(text: '  ', style: TextStyle(fontSize: 36.sp, color: ColorConst.btnFontColor)),
                              TextSpan(text: goal, style: TextStyle(fontSize: 36.sp, color: ColorConst.activeColor)),
                            ]),
                          ),
                        Container(
                          margin: EdgeInsets.only(top: 24.h, bottom: 50.h),
                          child: Divider(height: 1.h),
                        ),
                        LayoutBuilder(builder: (context, constraints) {
                          double width = (constraints.maxWidth - 220.w) / 2;
                          double height = 200.h;
                          return Row(
                            children: [
                              SizedBox(width: 60.w),
                              SizedBox(
                                width: width,
                                height: height,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(LocaleKeys.sports_duration_text.ts,
                                            style: TextStyle(color: ColorConst.secondaryFontColor, fontSize: 38.sp)),
                                        Text(logic.uTEPedSports.realTimeData.getDurationText, style: TextStyle(color: Colors.black, fontSize: 45.sp)),
                                      ],
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(LocaleKeys.sports_pace_text.ts, style: TextStyle(color: ColorConst.secondaryFontColor, fontSize: 38.sp)),
                                        Text(logic.uTEPedSports.realTimeData.getPaceText, style: TextStyle(color: Colors.black, fontSize: 45.sp)),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(width: 90.w),
                              SizedBox(
                                width: width,
                                height: height,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(LocaleKeys.sports_heart_rate_text.ts,
                                            style: TextStyle(color: ColorConst.secondaryFontColor, fontSize: 38.sp)),
                                        Text(logic.uTEPedSports.realTimeData.getHeartText, style: TextStyle(color: Colors.black, fontSize: 45.sp)),
                                      ],
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Container(
                                          width: 185.w,
                                          alignment: Alignment.centerLeft,
                                          child: Text(LocaleKeys.sports_calories_text.ts,
                                              style: TextStyle(color: ColorConst.secondaryFontColor, fontSize: 38.sp)),
                                        ),
                                        Container(
                                          alignment: Alignment.centerRight,
                                          child: Text(logic.uTEPedSports.realTimeData.getCalorieText,
                                              style: TextStyle(color: Colors.black, fontSize: 45.sp)),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(width: 60.w),
                            ],
                          );
                        }),
                      ],
                    );
                  }),
            ),
            Container(
                margin: EdgeInsets.fromLTRB(38.w, 29.h, 38.w, 100.h),
                height: 1280.h,
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  decoration: BoxDecoration(
                    boxShadow: state.isShowMap ? [BoxShadow(color: Colors.grey.withOpacity(0.7), blurRadius: 5)] : [],
                    borderRadius: BorderRadius.circular(60.r),
                  ),
                  child: Stack(
                    fit: StackFit.expand,
                    alignment: Alignment.center,
                    children: [
                      GetBuilder<MotionLogic>(
                          id: 'show_map',
                          builder: (_) {
                            return Visibility(
                              visible: state.isShowMap,
                              maintainSize: true,
                              maintainAnimation: true,
                              maintainState: true,
                              child: GoogleMap(
                                mapToolbarEnabled: false,
                                zoomControlsEnabled: false,
                                mapType: MapType.normal,
                                initialCameraPosition: const CameraPosition(target: LatLng(39.906217, 116.3912757), zoom: 17.0),
                                myLocationEnabled: false,
                                myLocationButtonEnabled: false,
                                polylines: {state.polyLine},
                                onMapCreated: (GoogleMapController controller) => logic.onMapCreated(controller),
                                markers: Set.from(state.markers),
                                // onCameraMove: (position) {
                                //   logger2.d(position.target.toString());
                                // },
                                // onCameraMoveStarted: () => logic.onCameraMoveStarted(),
                              ),
                            );
                          }),
                      GetBuilder<MotionLogic>(
                          id: 'sport_state',
                          builder: (_) {
                            return Visibility(
                                visible: state.isLock,
                                child: Positioned(
                                  bottom: 20.h,
                                  child: GestureDetector(
                                    onLongPressStart: (value) {
                                      isLongPress = true;
                                      timer = Timer.periodic(const Duration(milliseconds: 1), (timer) {
                                        if (!isLongPress) {
                                          return;
                                        }
                                        state.progressCount += 0.1;
                                        logic.setProgress();
                                        if (state.progressCount >= 100) {
                                          timer.cancel();
                                          state.progressCount = 0;
                                          logic.isLock(false);
                                        }
                                      });
                                    },
                                    onLongPressEnd: (value) {
                                      isLongPress = false;
                                      timer.cancel();
                                      state.progressCount = 0;
                                      logic.setProgress();
                                    },
                                    behavior: HitTestBehavior.opaque,
                                    child: Column(
                                      children: [
                                        Text(LocaleKeys.sports_press_unlock.ts, style: TextStyle(fontSize: 46.sp, color: ColorConst.btnFontColor),),
                                        SizedBox(height: 30.h,),
                                        Stack(
                                          children: [
                                            SizedBox(
                                              width: 296.w,
                                              height: 296.w,
                                              child: GetBuilder<MotionLogic>(
                                                id: 'unlock_progress',
                                                builder: (_) {
                                                  return CircularProgressIndicator(
                                                    value: state.progressCount / 100,
                                                    backgroundColor: ColorConst.accentColor.withAlpha(60),
                                                    valueColor: AlwaysStoppedAnimation<Color>(ColorConst.accentColor),
                                                    strokeWidth: 20.w,
                                                  );
                                                },
                                              ),
                                            ),
                                            Image.asset('assets/images/sports/icon_sport_locked.png', width: 296.w, height: 296.w),
                                          ],
                                        )
                                      ],
                                    ),
                                    // child:
                                  ),
                                ));
                          }),
                      GetBuilder<MotionLogic>(
                          id: 'sport_state',
                          builder: (ctrl) {
                            return Visibility(
                                visible: state.isPause,
                                child: Positioned(
                                    bottom: 20.h,
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        GestureDetector(
                                          child: Image.asset('assets/images/sports/icon_sport_stop.png', width: 362.w, height: 362.w),
                                          onTap: () => ctrl.uTEPedSports.stop(),
                                        ),
                                        GestureDetector(
                                          child: Image.asset('assets/images/sports/icon_sport_play.png', width: 362.w, height: 362.w),
                                          onTap: () => logic.isPause(false),
                                        ),
                                      ],
                                    )));
                          }),
                      GetBuilder<MotionLogic>(
                          id: 'sport_state',
                          builder: (_) {
                            return Visibility(
                                visible: !state.isPause && !state.isLock,
                                child: Positioned(
                                    bottom: 20.h,
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        // GestureDetector(
                                        //   child: Image.asset('assets/images/sports/icon_sport_setting.png', width: 260.w, height: 260.w),
                                        //   onTap: () {},
                                        // ),
                                        GestureDetector(
                                          child: Image.asset('assets/images/sports/icon_sport_pause.png', width: 320.w, height: 320.w),
                                          onTap: () => logic.isPause(true),
                                        ),
                                        GestureDetector(
                                          child: Image.asset('assets/images/sports/icon_sport_lock.png', width: 260.w, height: 260.w),
                                          onTap: () => logic.isLock(true),
                                        ),
                                      ],
                                    )));
                          }),
                    ],
                  ),
                )),
          ],
        ),
      ),
    );
  }
}
